package com.me.study.ui.activity.blue

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.me.study.R
import com.me.study.app.base.BaseActivity
import com.me.study.app.ext.goActivity
import com.me.study.app.laserRange.ACSUtility
import com.me.study.databinding.ActivityOperateBluetoothBinding
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.cos
import kotlin.math.sin


class OperateBluetoothActivity : BaseActivity<BaseViewModel, ActivityOperateBluetoothBinding>(),
    View.OnClickListener {

    private var mSelectedPort: ACSUtility.blePort? = null
    private lateinit var acsUtility: ACSUtility

    override fun layoutId() = R.layout.activity_operate_bluetooth

    override fun initView(savedInstanceState: Bundle?) {
        intent.extras?.let { b ->
            mSelectedPort = b.getParcelable(BluetoothDevice.EXTRA_DEVICE)
        }
        acsUtility = ACSUtility(this, ACSCallback())
        mDatabind.btnDataMeasure.setOnClickListener(this)
        mDatabind.btnDataClear.setOnClickListener(this)
        mDatabind.btnDataSave.setOnClickListener(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        acsUtility.closePort()
        acsUtility.closeACSUtility()
    }

    inner class ACSCallback : ACSUtility.IACSUtilityCallback {

        @SuppressLint("MissingPermission")
        override fun utilReadyForUse() {
            mSelectedPort?.let {
                val open = acsUtility.openPort(it)
                if (open) {
                    mDatabind.tvTitle.text = "${it._device.name}"
                }
            }
        }

        @SuppressLint("MissingPermission")
        override fun didFoundPort(newPort: ACSUtility.blePort?) {

        }

        override fun didFinishedEnumPorts() {

        }


        override fun didOpenPort(port: ACSUtility.blePort, bSuccess: Boolean) {

        }

        override fun didClosePort(port: ACSUtility.blePort?) {
            ToastUtils.showShort("连接断开")
            goActivity(SearchBluetoothActivity::class.java)
            this@OperateBluetoothActivity.finish()
        }

        override fun didPackageSended(succeed: Boolean) {

        }

        override fun didPackageReceived(port: ACSUtility.blePort, packageToSend: ByteArray) {
            // 距离
            var s = ACSUtility.bytesToHex(packageToSend)
            if (s.length != 34) {
                return
            }
            val sb = s.substring(6, 14)
            val parse = Integer.parseInt(sb, 16)
            val bd = BigDecimal(parse).divide(BigDecimal(10000), 3, RoundingMode.HALF_UP)
            val result = bd.toDouble()
            // 角度
            var resultAngle: Double
            var minusB: Boolean
            val angle = s.substring(14, 22)
            val code = isComplementaryCode(angle)
            if (code) {
                minusB = true
                val value = java.lang.Long.parseLong(angle, 16)
                val value2 = java.lang.Long.parseLong("FFFFFFFF", 16)
                val result = value2 - value + 1
                resultAngle =
                    BigDecimal(result).divide(BigDecimal(10), 2, RoundingMode.HALF_UP).toDouble()
            } else {
                minusB = false
                val angle16 = Integer.parseInt(angle, 16)
                val binaryString = Integer.toBinaryString(angle16)
                val decimalNumber: Int = Integer.parseInt(binaryString, 2)
                resultAngle =
                    BigDecimal(decimalNumber).divide(BigDecimal(10), 2, RoundingMode.HALF_UP)
                        .toDouble()
            }
            // 弧度
            val theta = Math.toRadians(resultAngle)
            // 高度
            val resultHeight = result * sin(theta)
            // 水平距离（底边长度）
            val base = result * cos(theta)
            val baseBig = BigDecimal(base).setScale(3, BigDecimal.ROUND_HALF_UP)
            val heightBig = BigDecimal(resultHeight).setScale(3, BigDecimal.ROUND_HALF_UP)
            runOnUiThread {
                if (minusB) {
                    mDatabind.angle.text = "-${resultAngle}°"
                } else {
                    mDatabind.angle.text = "${resultAngle}°"
                }
                mDatabind.bevelEdge.text = "${result}m"
                mDatabind.base.text = "${baseBig}m"
                mDatabind.height.text = "${heightBig}m"
            }

        }

        override fun heartbeatDebug() {

        }

        private fun isComplementaryCode(hexString: String): Boolean {
            // 将十六进制字符串转换为整数
            val intValue = java.lang.Long.parseLong(hexString, 16).toInt()
            return intValue < 0
        }


    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.btn_data_measure -> {
                val data = acsUtility.dataConversion("ATK001#")
                acsUtility.writePort(data)
            }
            R.id.btn_data_clear -> {
                val data = acsUtility.dataConversion("ATK009#")
                acsUtility.writePort(data)
            }
            R.id.btn_data_save -> {
                val data = acsUtility.dataConversion("ATK00A#")
                acsUtility.writePort(data)
            }
        }
    }


}
